/*************************************************************************
 *
 *  Copyright (C) 2013 Florian Dang <florian.coin@gmail.com>
 *
 *  This file is part of NatusVerse.
 *
 *  NatusVerse is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  NatusVerse is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with NatusVerse.  If not, see <http://www.gnu.org/licenses/>.
 *
 *************************************************************************/

#include "raytracer/objects/point.h"
#include "utils.h"

#include <stdio.h>
#include <cmath>
#include <cassert>

namespace raytracer
{
void Point::Print() const
{
	printf("(%.3f %.3f %.3f)", x(), y(), z());
}

Point Point::CrossProd(const Point& rhs) const
{
	Point result;

	result.set_x(y() * rhs.z() - rhs.y() * z());
	result.set_y(z() * rhs.x() - rhs.z() * x());
	result.set_z(x() * rhs.y() - rhs.x() * y());

	return result;
}

float Point::SquareNorm() const
{
	float norm = (*this) * (*this);
	assert(norm != 0.0f);

	return norm;
}

Point Point::Normalize()
{
	// This is not working :(
	// float squarenorm = this->SquareNorm();
	// (*this) = (*this) * InvSqrt(squarenorm);

	float invnorm = 1/sqrtf(this->SquareNorm());
	(*this) = (*this) * invnorm;

	return *this;
}
} // end namespace point

std::ostream& operator<< (std::ostream& os, raytracer::Point point)
{
	os << "x = " << point.x();
	os << "\ty=" << point.y();
	os << "\tz=" << point.z() << "\n";

	return os;
}

float operator* (const raytracer::Point& lhs,
				 const raytracer::Point& rhs)
{
	return  lhs.x() * rhs.x() + lhs.y() * rhs.y() + lhs.z() * rhs.z();
}

raytracer::Point operator% (const raytracer::Point& lhs,
							const raytracer::Point& rhs)
{
	return raytracer::Point(lhs.y() * rhs.z() - rhs.y() * lhs.z(),
				 lhs.z() * rhs.x() - rhs.z() * lhs.x(),
				 lhs.x() * rhs.y() - rhs.x() * lhs.y());
}

raytracer::Point operator* (const float scal, const raytracer::Point& rhs)
{
	return raytracer::Point(scal * rhs.x(),
							scal * rhs.y(),
							scal * rhs.z());
}
